<!doctype html>
<!--
    @license
    Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
    This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
    The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
    The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
    Code distributed by Google as part of the polymer project is also
    subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<script src="../../tools/chai/chai.js"></script>
<script src="../../tools/htmltest.js"></script>

<script src="../../../src/ShadowDOM/ShadowDOM.js"></script>
<script>
// Note: this test will navigate away from the page. It is designed to be run
// in an iframe. Use ShadowDOM/test/runner.html?grep=unload for running it by
// itself.

function runTest() {
  var assert = chai.assert;
  var doc = ShadowDOMPolyfill.wrap(document);
  var win = ShadowDOMPolyfill.wrap(window);

  // Note: IE gives `window` as the target for beforeunload/unload. Others give
  // document. It's not clear than anyone gets it right, my reading of the
  // current spec is target should be window for beforeunload, but is overridden
  // to be document for unload. Both events are dispatched on window:
  // http://www.whatwg.org/specs/web-apps/current-work/multipage/browsers.html#unloading-documents
  var expectedTarget = /Trident|Edge/.test(navigator.userAgent) ? win : doc;

  var beforeunloadCalled = 0;
  window.addEventListener('beforeunload', function(e) {
    beforeunloadCalled++;
    assert.equal(e.target, expectedTarget);
  });

  window.addEventListener('unload', function(e) {
    assert.equal(beforeunloadCalled, 1);
    assert.equal(e.target, expectedTarget);
    done();
  });

  location.href = 'about:blank';
}

document.addEventListener('DOMContentLoaded', function(e) {
  // Note: setTimeout makes IE happy. If document.readyState == 'interactive'
  // at the time we run the tests, IE won't fire an unload in the iframe.
  setTimeout(runTest, 0);
});

</script>
